
"""
Seccion donde se administra el logueo de usuarios
"""

from pyramid.httpexceptions import HTTPFound
from pyramid.security import authenticated_userid, remember, forget

from alpha.modelos import DBSession
from alpha.modelos import Usuario

"""
Vista login, valida la autenticacion de los usuarios e inicia sesion
"""

def login(request):
    login_url = request.route_url('login')
    referrer = request.url
    if referrer == login_url:
        referrer = '/' # never use the login form itself as came_from
    came_from = request.params.get('came_from', referrer)

    login = ''
    password = ''
   

    post_data = request.POST
    if 'login' in post_data:
        login = post_data['login']
        password = post_data['password']
        if Usuario.check_password(login, password):
            headers = remember(request, login)
            request.session.flash(u'Login satisfactorio')	    
            return HTTPFound(location = came_from,
                             headers = headers)
	request.session.flash(u'LOGIN FALLIDO')
        return HTTPFound(location = came_from,
                             mensaje = '')

    return dict(
		
        )

"""
Vista logout, cierra la sesion y redirije a la vista main
"""  
def logout(request):
    request.session.invalidate()
    request.session.flash(u'')
    headers = forget(request)
    return HTTPFound(location = request.route_url('main'),
                     headers = headers)
    
